//
//  SearchViewController.m
//  LiangYa_BObject
//
//  Created by dllo on 15/10/30.
//  Copyright © 2015年 YuHao. All rights reserved.
//

#import "SearchViewController.h"
#import "ClassContentData.h"
#import "ClassContentCollectionViewCell.h"
#import "BuyViewController.h"

@interface SearchViewController ()<UISearchBarDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UISearchBar *searchB;
@property (nonatomic, strong) NSString *keyWord;
@property (nonatomic, strong) NSMutableArray *goodDataArr;
@property (nonatomic, strong) UICollectionView *collectionV;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic, strong) UILabel *nothingL;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.searchB = [[UISearchBar alloc] init];
    _searchB.placeholder = @"请输入关键字";
    _searchB.delegate = self;
    _searchB.searchBarStyle = UISearchBarStyleDefault;
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    cancelBtn.frame = CGRectMake(0, 0, 40, 30);
    [cancelBtn setTitle:@" 取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    cancelBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [cancelBtn addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelBtn];
    
    self.navigationItem.titleView = self.searchB;
    
    [_searchB becomeFirstResponder];
    
    UICollectionViewFlowLayout *flowL = [[UICollectionViewFlowLayout alloc] init];
    flowL.itemSize = CGSizeMake((ScreenWidth - 30) / 2, 190);
    flowL.minimumInteritemSpacing = 10;
    flowL.minimumLineSpacing = 10;
    flowL.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.collectionV = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowL];
    _collectionV.backgroundColor = [UIColor whiteColor];
    _collectionV.delegate = self;
    _collectionV.dataSource = self;
    [self.view addSubview:_collectionV];
    _collectionV.backgroundColor = [UIColor clearColor];
    
    [_collectionV registerClass:[ClassContentCollectionViewCell class] forCellWithReuseIdentifier:@"searchcell"];
    
    self.nothingL = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, ScreenWidth, 100)];
    _nothingL.text = @"很抱歉,没有找到你想要的数据";
    _nothingL.textAlignment = NSTextAlignmentCenter;
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"nightstyle"]) {
        _nothingL.textColor = [UIColor whiteColor];
    }else{
        _nothingL.textColor = [UIColor blackColor];
    }
    [self.view addSubview:_nothingL];
    _nothingL.hidden = YES;
    
}

- (void)cancel
{
    [self.searchB resignFirstResponder];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _HUD.labelText = @"数据加载中...";
    
    [self dataHandler];
    [searchBar resignFirstResponder];
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
//    NSLog(@"%@", searchText);
    self.keyWord = searchText;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ClassContentData *classCD = [self.goodDataArr objectAtIndex:indexPath.item];
    BuyViewController *buyVC = [[BuyViewController alloc] init];
    buyVC.urlStr = classCD.buy_url;
    [self presentViewController:buyVC animated:YES completion:^{
        
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    NSLog(@"--------- %ld", _goodDataArr.count);
    return _goodDataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ClassContentCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"searchcell" forIndexPath:indexPath];
    
    ClassContentData *classCD = [self.goodDataArr objectAtIndex:indexPath.item];
    NSString *strH = [NSString stringWithFormat:@"[%@] %@ %@", classCD.brand_name, classCD.style_name, classCD.goods_name];

    [cell.imageV sd_setImageWithURL:classCD.imageC placeholderImage:[UIImage imageNamed:@"baikejiaju.png"]];
    if ([strH containsString:_keyWord]) {
        NSRange colorfulRange = [strH rangeOfString:_keyWord];
        NSRange headRange = NSMakeRange(0, colorfulRange.location);
        NSRange commonRange = NSMakeRange(colorfulRange.length + colorfulRange.location, strH.length - colorfulRange.length - colorfulRange.location);
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:strH];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:colorfulRange];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:headRange];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:commonRange];
        
        cell.content.attributedText = str;
    }else{
        cell.content.text = strH;
    }
//    cell.content.text = [NSString stringWithFormat:@"[%@] %@ %@", classCD.brand_name, classCD.style_name, classCD.goods_name];
    cell.price.text = classCD.price;
    cell.soldNum.text = classCD.soldNum;
    
    return cell;
}

- (void)dataHandler
{
    NSString *str = [NSString stringWithFormat:@"http://www.meilele.com/solr_api/newjson/category-9999/?keywords=%@&from=c", self.keyWord];
//    NSLog(@"%@", str);
    
    self.goodDataArr = [NSMutableArray array];
    
    [AFRequdstAndLoad dataURLStr:str datahand:^(id object) {
        
        if (object) {
            [_HUD removeFromSuperview];
        }
        
        NSArray *goodArr = [object objectForKey:@"goods_list"];
        for (NSDictionary *goodDic in goodArr) {
            ClassContentData *classCD = [[ClassContentData alloc] init];
            [classCD setValuesForKeysWithDictionary:goodDic];
            
            [self.goodDataArr addObject:classCD];
        }
        [self.collectionV reloadData];
        if (self.goodDataArr.count == 0) {
            _nothingL.hidden = NO;
        }else{
            _nothingL.hidden = YES;
        }
    }];
//    NSLog(@".>>>>>>>>>>>>>>%@", self.goodDataArr);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
